﻿using Hydrogen.Cmd.Interfaces;
using Hydrogen.Console;
using System;
using System.Collections.Generic;
using System.IO;
using SConsole = System.Console;

namespace Hydrogen.Cmd.Commands
{
    /// <summary>
    /// 根据关键词搜索文件
    /// </summary>
    [CommandFlag("se", "search")]
    public class SearchFileCommand : CommandBase
    {
        public new static string Discription => "find Files with key word.";

        public override void Invoke(params string[] args)
        {
            string[] files = new string[0];
            List<string> temp = new List<string>();
            if (args.Length < 2)
            {
                //files = Directory.GetFiles(Environment.CurrentDirectory, "*", SearchOption.AllDirectories);
                GetFile(Environment.CurrentDirectory, "*", ref temp);
                files = temp.ToArray();
            }
            else
            {
                //files = Directory.GetFiles(Environment.CurrentDirectory, args[1], SearchOption.AllDirectories);
                GetFile(Environment.CurrentDirectory, args[1], ref temp);
                files = temp.ToArray();
            }
            if (files.Length <= 0) ConsoleLog.Log("搜索结果为空......也许是无权限读取，试试管理员模式？");
            else ConsoleLog.Log("搜索结束，共 {0} 条结果。", files.Length);

            List<string> list = new List<string>();
            //foreach (var item in files)
            for (int i = 0; i < files.Length; i++)
            {
                int index = i;
                list.Add(string.Format("{0}", Path.GetFileName(files[index])));
            }
            DisplayFilesInConsole(list.ToArray(), files);

            string inputStr = "1";
            while (!string.IsNullOrEmpty(inputStr))
            {
                ConsoleLog.WriteColor("输入编号打开目录，直接回车结束：", ConsoleColor.White);
                inputStr = SConsole.ReadLine();
                if (string.IsNullOrEmpty(inputStr)) return;
                int ind = -1;
                if (int.TryParse(inputStr, out ind) && ind >= 0 && ind < files.Length)
                {
                    //打开
                    var p = System.Diagnostics.Process.Start("Explorer.exe", Path.GetDirectoryName(files[ind]));
                }
            }
        }

        private void DisplayFilesInConsole(string[] files, string[] filePath)
        {
            for (int i = 0; i < files.Length; i++)
            {
                if (i < files.Length - 1) SConsole.Write("\t┣  ");
                else SConsole.Write("\t┗  ");

                SConsole.ForegroundColor = ConsoleColor.Cyan;
                SConsole.Write("[{0}] {1}", i, files[i]);
                SConsole.ForegroundColor = ConsoleColor.Green;
                SConsole.WriteLine("\t{0}", filePath[i]);
                SConsole.ResetColor();
            }
        }

        private void GetFile(string path, string searchPattern, ref List<string> result)
        {
            var topDirs = Directory.GetDirectories(path, "*", SearchOption.TopDirectoryOnly);

            result.AddRange(Directory.GetFiles(path, searchPattern));
            foreach (var item in topDirs)
            {
                try
                {
                    GetFile(item, searchPattern, ref result);
                }
                catch (Exception e)
                {
                    ConsoleLog.LogError(e.Message);
                }
            }
        }
    }
}
